package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.User;
import com.tree.backend.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author tree
 * @since 2025-10-23
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;

    // 登录接口
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        String Token =  userService.login(user);
        return Result.success(Token);
    }
    
    // 获取用户列表（分页）
    @GetMapping("/list")
    public Result<IPage<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            String username) {
        Page<User> page = new Page<>(pageNum, pageSize);
        User queryUser = new User();
        queryUser.setUsername(username);
        IPage<User> userList = userService.getUserList(page, queryUser);
        return Result.success(userList);
    }
    
    // 根据ID获取用户
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }
    
    // 添加用户
    @PostMapping
    public Result<Boolean> addUser(@RequestBody User user) {
        boolean result = userService.addUser(user);
        return Result.success(result);
    }
    
    // 更新用户
    @PutMapping
    public Result<Boolean> updateUser(@RequestBody User user) {
        boolean result = userService.updateUser(user);
        return Result.success(result);
    }
    
    // 删除用户
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        boolean result = userService.deleteUser(id);
        return Result.success(result);
    }
}
